﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Telerik.WinControls;
using System.IO;
using Telerik.WinControls.UI;
using Telerik.WinControls.Data;
using log4net;
using System.Text.RegularExpressions;

namespace QuanLyNhaSach
{
    public partial class frmTraHangNhaCungCap : Form
    {
        //Tao Parttern Seleton
        static frmTraHangNhaCungCap doituong = null;
        public static frmTraHangNhaCungCap TaoDoiTuong()
        {
            if (doituong == null)
                doituong = new frmTraHangNhaCungCap();
            return doituong;
        }
        string manv_PTH = frmDangNhap.maNV_FromDangNhap;
        string tennv_PTH = frmDangNhap.hoTenNV_FormDangNhap;
        public frmTraHangNhaCungCap()
        {
            InitializeComponent();
        }

        #region "Khai báo thông tin biến"
        sv_QuanLyNhaSach.AdapterClient xuli = new sv_QuanLyNhaSach.AdapterClient();
        private ILog logger;

        public bool them { get; set; }

        int vitri;
        int stt = 0;

        double tongtien = 0;
        double tongtienhang = 0;
        double tienTamUng = 0;
        double tienthue = 0;
        double tienConLai = 0;

        float mucThue;

        string mahang;
        string tenhang;
        string dongia;
        string soluongtra;
        float khuyenmai;
        string thanhtien;
        string dvt;
        public string manv = frmDangNhap.maNV_FromDangNhap;
        #endregion

        #region "Ham chuyen so thanh chu"
        private static string Chu(string gNumber)
        {
            string result = "";
            switch (gNumber)
            {
                case "0":
                    result = "không";
                    break;
                case "1":
                    result = "một";
                    break;
                case "2":
                    result = "hai";
                    break;
                case "3":
                    result = "ba";
                    break;
                case "4":
                    result = "bốn";
                    break;
                case "5":
                    result = "năm";
                    break;
                case "6":
                    result = "sáu";
                    break;
                case "7":
                    result = "bảy";
                    break;
                case "8":
                    result = "tám";
                    break;
                case "9":
                    result = "chín";
                    break;
            }
            return result;
        }
        private static string Donvi(string so)
        {
            string Kdonvi = "";

            if (so.Equals("1"))
                Kdonvi = "";
            if (so.Equals("2"))
                Kdonvi = "nghìn";
            if (so.Equals("3"))
                Kdonvi = "triệu";
            if (so.Equals("4"))
                Kdonvi = "tỷ";
            if (so.Equals("5"))
                Kdonvi = "nghìn tỷ";
            if (so.Equals("6"))
                Kdonvi = "triệu tỷ";
            if (so.Equals("7"))
                Kdonvi = "tỷ tỷ";

            return Kdonvi;
        }
        private static string Tach(string tach3)
        {
            string Ktach = "";
            if (tach3.Equals("000"))
                return "";
            if (tach3.Length == 3)
            {
                string tr = tach3.Trim().Substring(0, 1).ToString().Trim();
                string ch = tach3.Trim().Substring(1, 1).ToString().Trim();
                string dv = tach3.Trim().Substring(2, 1).ToString().Trim();
                if (tr.Equals("0") && ch.Equals("0"))
                    Ktach = " không trăm lẻ " + Chu(dv.ToString().Trim()) + " ";
                if (!tr.Equals("0") && ch.Equals("0") && dv.Equals("0"))
                    Ktach = Chu(tr.ToString().Trim()).Trim() + " trăm ";
                if (!tr.Equals("0") && ch.Equals("0") && !dv.Equals("0"))
                    Ktach = Chu(tr.ToString().Trim()).Trim() + " trăm lẻ " + Chu(dv.Trim()).Trim() + " ";
                if (tr.Equals("0") && Convert.ToInt32(ch) > 1 && Convert.ToInt32(dv) > 0 && !dv.Equals("5"))
                    Ktach = " không trăm " + Chu(ch.Trim()).Trim() + " mươi " + Chu(dv.Trim()).Trim() + " ";
                if (tr.Equals("0") && Convert.ToInt32(ch) > 1 && dv.Equals("0"))
                    Ktach = " không trăm " + Chu(ch.Trim()).Trim() + " mươi ";
                if (tr.Equals("0") && Convert.ToInt32(ch) > 1 && dv.Equals("5"))
                    Ktach = " không trăm " + Chu(ch.Trim()).Trim() + " mươi lăm ";
                if (tr.Equals("0") && ch.Equals("1") && Convert.ToInt32(dv) > 0 && !dv.Equals("5"))
                    Ktach = " không trăm mười " + Chu(dv.Trim()).Trim() + " ";
                if (tr.Equals("0") && ch.Equals("1") && dv.Equals("0"))
                    Ktach = " không trăm mười ";
                if (tr.Equals("0") && ch.Equals("1") && dv.Equals("5"))
                    Ktach = " không trăm mười lăm ";
                if (Convert.ToInt32(tr) > 0 && Convert.ToInt32(ch) > 1 && Convert.ToInt32(dv) > 0 && !dv.Equals("5"))
                    Ktach = Chu(tr.Trim()).Trim() + " trăm " + Chu(ch.Trim()).Trim() + " mươi " + Chu(dv.Trim()).Trim() + " ";
                if (Convert.ToInt32(tr) > 0 && Convert.ToInt32(ch) > 1 && dv.Equals("0"))
                    Ktach = Chu(tr.Trim()).Trim() + " trăm " + Chu(ch.Trim()).Trim() + " mươi ";
                if (Convert.ToInt32(tr) > 0 && Convert.ToInt32(ch) > 1 && dv.Equals("5"))
                    Ktach = Chu(tr.Trim()).Trim() + " trăm " + Chu(ch.Trim()).Trim() + " mươi lăm ";
                if (Convert.ToInt32(tr) > 0 && ch.Equals("1") && Convert.ToInt32(dv) > 0 && !dv.Equals("5"))
                    Ktach = Chu(tr.Trim()).Trim() + " trăm mười " + Chu(dv.Trim()).Trim() + " ";

                if (Convert.ToInt32(tr) > 0 && ch.Equals("1") && dv.Equals("0"))
                    Ktach = Chu(tr.Trim()).Trim() + " trăm mười ";
                if (Convert.ToInt32(tr) > 0 && ch.Equals("1") && dv.Equals("5"))
                    Ktach = Chu(tr.Trim()).Trim() + " trăm mười lăm ";

            }


            return Ktach;

        }
        public static string So_chu(double gNum)
        {
            if (gNum == 0)
                return "Không đồng";

            string lso_chu = "";
            string tach_mod = "";
            string tach_conlai = "";
            double Num = Math.Round(gNum, 0);
            string gN = Convert.ToString(Num);
            int m = Convert.ToInt32(gN.Length / 3);
            int mod = gN.Length - m * 3;
            string dau = "[+]";

            // Dau [+ , - ]
            if (gNum < 0)
                dau = "[-]";
            dau = "";

            // Tach hang lon nhat
            if (mod.Equals(1))
                tach_mod = "00" + Convert.ToString(Num.ToString().Trim().Substring(0, 1)).Trim();
            if (mod.Equals(2))
                tach_mod = "0" + Convert.ToString(Num.ToString().Trim().Substring(0, 2)).Trim();
            if (mod.Equals(0))
                tach_mod = "000";
            // Tach hang con lai sau mod :
            if (Num.ToString().Length > 2)
                tach_conlai = Convert.ToString(Num.ToString().Trim().Substring(mod, Num.ToString().Length - mod)).Trim();

            ///don vi hang mod 
            int im = m + 1;
            if (mod > 0)
                lso_chu = Tach(tach_mod).ToString().Trim() + " " + Donvi(im.ToString().Trim());
            /// Tach 3 trong tach_conlai

            int i = m;
            int _m = m;
            int j = 1;
            string tach3 = "";
            string tach3_ = "";

            while (i > 0)
            {
                tach3 = tach_conlai.Trim().Substring(0, 3).Trim();
                tach3_ = tach3;
                lso_chu = lso_chu.Trim() + " " + Tach(tach3.Trim()).Trim();
                m = _m + 1 - j;
                if (!tach3_.Equals("000"))
                    lso_chu = lso_chu.Trim() + " " + Donvi(m.ToString().Trim()).Trim();
                tach_conlai = tach_conlai.Trim().Substring(3, tach_conlai.Trim().Length - 3);

                i = i - 1;
                j = j + 1;
            }
            if (lso_chu.Trim().Substring(0, 1).Equals("k"))
                lso_chu = lso_chu.Trim().Substring(10, lso_chu.Trim().Length - 10).Trim();
            if (lso_chu.Trim().Substring(0, 1).Equals("l"))
                lso_chu = lso_chu.Trim().Substring(2, lso_chu.Trim().Length - 2).Trim();
            if (lso_chu.Trim().Length > 0)
                lso_chu = dau.Trim() + " " + lso_chu.Trim().Substring(0, 1).Trim().ToUpper() + lso_chu.Trim().Substring(1, lso_chu.Trim().Length - 1).Trim() + " đồng chẵn.";

            return lso_chu.ToString().Trim();

        }
        #endregion

        private void frmTraHangNhaCungCap_Load(object sender, EventArgs e)
        {
            //Enter
            this.KeyDown += new KeyEventHandler(frmTraHangNhaCungCap_KeyDown);
            txt_SoChungTu.KeyDown += new KeyEventHandler(txt_SoChungTu_KeyDown);
            mcbb_KhoHang.KeyDown += new KeyEventHandler(mcbb_KhoHang_KeyDown);
            mccb_NhaCungCap.KeyDown += new KeyEventHandler(mccb_NhaCungCap_KeyDown);
            mccb_TenMatHang.KeyDown += new KeyEventHandler(mccb_TenMatHang_KeyDown);
            txt_DonGia.KeyDown += new KeyEventHandler(txt_DonGia_KeyDown);
            txt_SoLuongTra.KeyDown += new KeyEventHandler(txt_SoLuongTra_KeyDown);
            btn_ChuyenXuong.KeyDown += new KeyEventHandler(btn_ChuyenXuong_KeyDown);
            btn_Luu.KeyDown += new KeyEventHandler(btn_Luu_KeyDown);
            //-----
            logger = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
            dtp_NgayTra.Value = DateTime.Now;
            try
            {
                //Lay Ten Nhan Vien
                txt_NhanVien.Text = tennv_PTH;

                //Load DS Hoa Don Mua Hang
                
                Load_NCC();
                Load_Kho();
            }
            catch (Exception ex)
            {
                logger.Error("Error: " + ex.Message);
            }
           
        }
        DataSet ds_ton;
        private void mccb_NhaCungCap_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                if (mccb_NhaCungCap.SelectedIndex != -1)
                {
                    if (mcbb_KhoHang.SelectedIndex != -1)
                    {
                        txt_DiaChiNhaCC.Text = mccb_NhaCungCap.EditorControl.Rows[mccb_NhaCungCap.SelectedIndex].Cells["diachincc"].Value.ToString();
                        DataSet ds = new DataSet();
                        ds.ReadXml(new StringReader(xuli.selectqueryByText("select MaMH,TenMH,DonGiaNhap from MatHang where MaMH in(select distinct MaMH from HoaDonNhapHang nh,CTNhapHang ct,NhaCungCap ncc where ct.MaHDNH=nh.MaHDNH and nh.MaNCC=ncc.MaNCC and ncc.MaNCC like '" + mccb_NhaCungCap.SelectedValue.ToString().Trim() + "%')")));
                        if (ds.Tables.Count > 0)
                        {
                            mccb_TenMatHang.DataSource = ds.Tables[0];
                            mccb_TenMatHang.DisplayMember = "TenMH";
                            mccb_TenMatHang.ValueMember = "MaMH";
                        }
                        DataSet ds1 = new DataSet();

                        ds1.ReadXml(new StringReader(xuli.BaoCaoXuatNhapTon(DateTime.Now, DateTime.Now, mcbb_KhoHang.SelectedValue.ToString().Trim(), mccb_TenMatHang.SelectedValue.ToString().Trim())));
                        if (ds1.Tables.Count > 0)
                        {
                            txt_SoLuongTra.Text = ds1.Tables[0].Rows[0]["TongSLTon"].ToString();
                        }
                        ds_ton = new DataSet();
                        ds_ton.ReadXml(new StringReader(xuli.BaoCaoXuatNhapTon(DateTime.Now, DateTime.Now, mcbb_KhoHang.SelectedValue.ToString().Trim(), "")));
                    }
                }
                else
                {
                }
                mccb_TenMatHang.SelectedIndex = -1;
            }
            catch { }
               
        }
        private void Load_NCC()
        {
            DataSet ds = new DataSet();
            ds.ReadXml(new StringReader(xuli.selectqueryByText("select mancc,tenncc,diachincc from nhacungcap where MaNCC <> 'NCC0000'")));
            if (ds.Tables.Count > 0)
            {
                mccb_NhaCungCap.DataSource = ds.Tables[0];
                mccb_NhaCungCap.DisplayMember = "tenncc";
                mccb_NhaCungCap.ValueMember = "mancc";
                 mccb_NhaCungCap.SelectedIndex = -1;
            }
            FilterDescriptor des_ncc = new FilterDescriptor(this.mccb_NhaCungCap.DisplayMember, FilterOperator.StartsWith, string.Empty);
            mccb_NhaCungCap.EditorControl.FilterDescriptors.Add(des_ncc);
           
        }

        private void Load_Kho()
        {
            DataSet ds = new DataSet();
            ds.ReadXml(new StringReader(xuli.LayDS_Kho()));
            if (ds.Tables.Count > 0)
            {
                mcbb_KhoHang.DataSource = ds.Tables[0];
                mcbb_KhoHang.DisplayMember = "tenkho";
                mcbb_KhoHang.ValueMember = "makho";
            }
            FilterDescriptor des_kho = new FilterDescriptor(this.mcbb_KhoHang.DisplayMember, FilterOperator.StartsWith, string.Empty);
            mcbb_KhoHang.EditorControl.FilterDescriptors.Add(des_kho);
            mcbb_KhoHang.SelectedIndex = -1;
        }

        void txt_DonGia_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.Enter)
                btn_ChuyenXuong.Focus();
        }

        void btn_Luu_KeyDown(object sender, KeyEventArgs e)
        {
            
        }

        void btn_ChuyenXuong_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.Enter)
                mccb_TenMatHang.Focus();
        }

        void txt_SoLuongTra_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.Enter)
                btn_ChuyenXuong.Focus();
        }

        void mccb_TenMatHang_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.Enter)
                txt_SoLuongTra.Focus();
        }

        void mccb_NhaCungCap_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.Enter)
                mccb_TenMatHang.Focus();
        }

        void mcbb_KhoHang_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.Enter)
                mccb_NhaCungCap.Focus();
        }

        void txt_SoChungTu_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.Enter)
                mcbb_KhoHang.Focus();
        }

        void frmTraHangNhaCungCap_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.F3)
                Luu();
        }

        private void Load_DS_HoaDonMuaHang()
        {
            

        }        

        private void mcbb_HoaDonMuaHang_SelectedIndexChanged(object sender, EventArgs e)
        {


        }

        private void mccb_TenMatHang_SelectedIndexChanged(object sender, EventArgs e)
        {
            errorProvider1.Clear();
            if (mccb_TenMatHang.Text == "")
            {
                txt_MaMatHang.Text = "";
                txt_DonGia.Text = "0";
                txt_SoLuongTra.Text = "1";
                txt_ThanhTien.Text = "0";
                ddl_DVT.Text = "";
            }
            else
            {
                try
                {
                    txt_MaMatHang.Text = mccb_TenMatHang.EditorControl.Rows[mccb_TenMatHang.SelectedIndex].Cells["MaMH"].Value.ToString();
                    txt_DonGia.Text = double.Parse(mccb_TenMatHang.EditorControl.Rows[mccb_TenMatHang.SelectedIndex].Cells["DonGiaNhap"].Value.ToString()).ToString("#,##"); ;
                    DataSet ds2 = new DataSet();
                    ds2.ReadXml(new StringReader(xuli.BaoCaoXuatNhapTon(DateTime.Now, DateTime.Now, mcbb_KhoHang.SelectedValue.ToString().Trim(), mccb_TenMatHang.SelectedValue.ToString().Trim())));
                    if (ds2.Tables.Count > 0)
                    {                        
                        txt_SoLuongTra.Text = ds2.Tables[0].Rows[0]["TongSLTon"].ToString();
                        kt_soluong = int.Parse(ds2.Tables[0].Rows[0]["TongSLTon"].ToString());
                    }
                    else
                        txt_SoLuongTra.Text = "0";
                }
                catch (Exception ex)
                {

                }
            }
        }
        int kt_soluong;
        private void txt_SoLuongTra_TextChanged(object sender, EventArgs e)
        {
            if (txt_SoLuongTra.Text.Length != 0)
            {
                if (txt_DonGia.Text.Length != 0)
                {
                    double thanhtien = double.Parse(txt_SoLuongTra.Text) * double.Parse(txt_DonGia.Text);
                    txt_ThanhTien.Text = thanhtien.ToString("#,##0");
                }

            }
        }

        private void txt_SoLuongTra_Leave(object sender, EventArgs e)
        {

        }

        private void btn_ChuyenXuong_Click(object sender, EventArgs e)
        {
            errorProvider1.Clear();
            if (txt_MaMatHang.Text == "")
            {
                errorProvider1.SetError(txt_MaMatHang, "Chưa chọn mặt hàng");
                txt_MaMatHang.Focus();
                return;
            }
            if (txt_SoLuongTra.Text.Trim() == "" || double.Parse(txt_SoLuongTra.Text) == 0)
            {
                errorProvider1.SetError(txt_SoLuongTra, "Số lượng không hợp lệ");
                txt_SoLuongTra.Focus();
                return;
            }
            if (txt_DonGia.Text == "" || double.Parse(txt_DonGia.Text) == 0)
            {
                errorProvider1.SetError(txt_DonGia, "Đơn giá không hợp lệ");
                txt_DonGia.Focus();
                return;
            }
            if (gv_ThongTinMatHangTra.Rows.Count > 0)
            {
                //Tang so luong va thay doi tong thanh tien + Truong hop gia tien khac nhau
                for (int i = 0; i < gv_ThongTinMatHangTra.Rows.Count; i++)
                {
                    if (mccb_TenMatHang.SelectedValue.ToString().Trim() == gv_ThongTinMatHangTra.Rows[i].Cells["MaMH"].Value.ToString().Trim() && txt_DonGia.Text.Trim() == gv_ThongTinMatHangTra.Rows[i].Cells["DonGia"].Value.ToString().Trim())
                    {
                        if (kt_soluong < int.Parse(gv_ThongTinMatHangTra.Rows[i].Cells["SoLuongTra"].Value.ToString()) + int.Parse(txt_SoLuongTra.Text.Trim()))
                        {
                            errorProvider1.SetError(txt_SoLuongTra, "Số lượng không đủ");
                            txt_SoLuongTra.Focus();
                            return;
                        }
                        gv_ThongTinMatHangTra.Rows[i].Cells["SoLuongTra"].Value = (int.Parse(gv_ThongTinMatHangTra.Rows[i].Cells["SoLuongTra"].Value.ToString()) + int.Parse(txt_SoLuongTra.Text.Trim())).ToString("#,##0");
                        gv_ThongTinMatHangTra.Rows[i].Cells["ThanhTien"].Value = (int.Parse(gv_ThongTinMatHangTra.Rows[i].Cells["SoLuongTra"].Value.ToString()) * double.Parse(gv_ThongTinMatHangTra.Rows[i].Cells["DonGia"].Value.ToString()) - int.Parse(gv_ThongTinMatHangTra.Rows[i].Cells["SoLuongTra"].Value.ToString()) * double.Parse(gv_ThongTinMatHangTra.Rows[i].Cells["DonGia"].Value.ToString()) * double.Parse(gv_ThongTinMatHangTra.Rows[i].Cells["KhuyenMai"].Value.ToString()) / 100).ToString("#,##0");
                        //Tinh tong tien hang
                        tongtienhang = 0;
                        for (int j = 0; j < gv_ThongTinMatHangTra.Rows.Count; j++)
                        {
                            tongtienhang += double.Parse(gv_ThongTinMatHangTra.Rows[j].Cells["ThanhTien"].Value.ToString());
                        }
                        txt_TongTienHang.Text = tongtienhang.ToString("#,##0");
                        mccb_TenMatHang.Focus();
                        return;
                    }
                }
            }
            //Gan gia tri cho bien
            mahang = txt_MaMatHang.Text;
            tenhang = mccb_TenMatHang.Text.Trim();
            soluongtra = txt_SoLuongTra.Text;
            dongia = txt_DonGia.Text;
            khuyenmai = float.Parse(txt_KhuyenMai.Text);
            thanhtien = txt_ThanhTien.Text;
            if (gv_ThongTinMatHangTra.Rows.Count != 0)
                vitri = gv_ThongTinMatHangTra.Rows.Count;
            else
                vitri = 0;
            //them mat hang xuong girdview                
            gv_ThongTinMatHangTra.Rows.AddNew();
            gv_ThongTinMatHangTra.Rows[vitri].Cells["MaMH"].Value = mahang;
            gv_ThongTinMatHangTra.Rows[vitri].Cells["TenMH"].Value = tenhang;
            gv_ThongTinMatHangTra.Rows[vitri].Cells["SoLuongTra"].Value = soluongtra;
            gv_ThongTinMatHangTra.Rows[vitri].Cells["DonGia"].Value = dongia;
            gv_ThongTinMatHangTra.Rows[vitri].Cells["KhuyenMai"].Value = khuyenmai;
            gv_ThongTinMatHangTra.Rows[vitri].Cells["ThanhTien"].Value = thanhtien;
            mcbb_KhoHang.Enabled = false;
            mccb_NhaCungCap.Enabled = false;
            //Thêm nút xóa trong GridView          
            if (gv_ThongTinMatHangTra.Columns.GetColumnByFieldName("xoa").Length == 0)
            {
                GridViewCommandColumn btnColumn = new GridViewCommandColumn();
                btnColumn.FieldName = "xoa";
                btnColumn.Name = "xoa";
                btnColumn.UseDefaultText = true;
                btnColumn.DefaultText = "Xóa";
                gv_ThongTinMatHangTra.Columns.Insert(gv_ThongTinMatHangTra.Columns.Count, btnColumn);
            }
            //Tao STT cho GridView
            if (txt_MucThue.Text.Length != 0)
            {
                tongtienhang = 0;
                tongtien = 0;
                for (int i = 0; i < gv_ThongTinMatHangTra.Rows.Count; i++)
                {
                    gv_ThongTinMatHangTra.Rows[i].Cells["STT"].Value = i + 1;
                    //Tinh Tong Tien
                    tongtienhang += double.Parse(gv_ThongTinMatHangTra.Rows[i].Cells["ThanhTien"].Value.ToString());
                }
                txt_TongTienHang.Text = tongtienhang.ToString("#,##0");
                tongtien = tongtienhang + double.Parse(txt_TienThue.Text);
                txt_TongTienCoTinhThue.Text = tongtien.ToString("#,##0");
                txt_TienBangChu.Text = So_chu(tongtien);
            }
            //Xoa bo thong tin trong cac o mat hang
            txt_MaMatHang.Text = "";
            mccb_TenMatHang.SelectedIndex = -1;
            txt_SoLuongTra.Text = "0";
            txt_DonGia.Text = "0";
            ddl_DVT.Text = "";
            txt_ThanhTien.Text = "0";
            txt_KhuyenMai.Text = "0";
            mccb_TenMatHang.Focus();
        }

        private void btn_Luu_Click(object sender, EventArgs e)
        {
            Luu();
        }

        private void Luu()
        {
            errorProvider1.Clear();
            if (txt_SoChungTu.Text.Trim() == "")
            {
                errorProvider1.SetError(txt_SoChungTu, "Số chứng từ không được bỏ trống");
                txt_SoChungTu.Focus();
                return;
            }

            if (gv_ThongTinMatHangTra.Rows.Count == 0)
            {
                    lbl_ThongBao.Text = "Chưa có dữ liệu trả hàng. Vui lòng nhập lại";
                    errorProvider1.RightToLeft = false;
                    errorProvider1.SetError(lbl_ThongBao, "Xem lại thông tin trên lưới.");
                    return;
            }
            else
            {
                for (int i = 0; i < gv_ThongTinMatHangTra.Rows.Count; i++)
                    for (int j = 0; j < ds_ton.Tables[0].Rows.Count; j++)
                        if (gv_ThongTinMatHangTra.Rows[i].Cells["MaMH"].Value.ToString().Trim() == ds_ton.Tables[0].Rows[j]["MaMH"].ToString().Trim())
                        {
                            if (int.Parse(gv_ThongTinMatHangTra.Rows[i].Cells["SoLuongTra"].Value.ToString().Trim()) > int.Parse(ds_ton.Tables[0].Rows[j]["TongSLTon"].ToString().Trim()))
                            {
                                lbl_ThongBao.Text = "Số lượng nhập vào lớn hơn số lượng tồn. Vui lòng nhập lại";
                                errorProvider1.RightToLeft = false;
                                errorProvider1.SetError(lbl_ThongBao, "Xem lại thông tin trên lưới.");
                                return;
                            }
                        }
                {
                    //Them vao Phieu Dat Hang NCC
                    //Lay MaDHNCC moi Nhat theo Kieu: "Đặt hàng NCC: DHNCC+2012(năm hiện tại)+03(Tháng hiện tại)+XXXX"
                    string maTHNCC = Lay_MaMoiNhat();
                    string maKho = mcbb_KhoHang.SelectedValue.ToString();
                    string maNCC = mccb_NhaCungCap.SelectedValue.ToString();
                    string maSoThue = txt_MaSoThue.Text;
                    string nguoiNhanTra = txt_NguoiNhanTra.Text;
                    DateTime ngayTra = dtp_NgayTra.Value;
                    string soChungTu = txt_SoChungTu.Text;
                    string ghiChuTH = txt_Ghichu.Text;
                    double tongDonHang = tongtien;

                    //Xu li them vao bang PhieuTraHangNCC
                    if (!xuli.InsertPhieuTraHangNCC(maTHNCC, manv, maKho, maNCC, maSoThue, ngayTra, nguoiNhanTra, soChungTu, ghiChuTH, tongDonHang))
                    {
                        MessageBox.Show("Loi Them Phieu Dat hang NCC");
                        return;
                    }
                    //Duyet qua Gridview de them vao bang Chi Tiet Dat Hang NCC
                    else
                    {
                        for (int i = 0; i < gv_ThongTinMatHangTra.Rows.Count; i++)
                        {
                            string maMH = gv_ThongTinMatHangTra.Rows[i].Cells["MaMH"].Value.ToString().Trim();
                            int soLuongTra = int.Parse(gv_ThongTinMatHangTra.Rows[i].Cells["SoLuongTra"].Value.ToString());
                            double donGia = double.Parse(gv_ThongTinMatHangTra.Rows[i].Cells["DonGia"].Value.ToString());
                            float chietKhau = float.Parse(txt_KhuyenMai.Text);
                            double thanhTien = double.Parse(gv_ThongTinMatHangTra.Rows[i].Cells["ThanhTien"].Value.ToString());
                            //Them tung chi tiet vao CT Tra Hang NCC
                            if (!xuli.InsertCTTraHangNCC(maMH, maTHNCC, soLuongTra, donGia, chietKhau, thanhTien))
                            {
                                MessageBox.Show("Loi Them Chi Tiet Phieu Dat hang NCC");
                                return;
                            }
                        }
                        MessageBox.Show("Lưu thành công");
                        if (check_in.Checked == true)
                        {
                            Report.frm_In_TraHangNCC trahangncc = new Report.frm_In_TraHangNCC();
                            trahangncc.MaTHNCC = maTHNCC;
                            trahangncc.ShowDialog();
                        }
                        Load_Kho();
                        Load_NCC();
                        dtp_NgayTra.Text = DateTime.Now.ToString();
                        mccb_NhaCungCap.Enabled = true;
                        mcbb_KhoHang.Enabled = true;
                        mcbb_KhoHang.SelectedIndex = -1;
                        mccb_NhaCungCap.SelectedIndex = -1;
                        mccb_TenMatHang.SelectedIndex = -1;
                        txt_MaMatHang.Text = "";
                        txt_DiaChiNhaCC.Text = "";
                        txt_NguoiNhanTra.Text = "";
                        txt_MaSoThue.Text = "";
                        gv_ThongTinMatHangTra.Rows.Clear();
                        txt_SoLuongTra.Text = "0";
                        txt_KhuyenMai.Text = "0";
                        txt_DonGia.Text = "0";
                        txt_ThanhTien.Text = "0";
                        txt_TongTienHang.Text = "0";
                        txt_TongTienCoTinhThue.Text = "0";
                        txt_SoChungTu.Text = "";
                        txt_Ghichu.Text = "";
                        txt_TienBangChu.Text="Không chẵn";
                        txt_MucThue.Text = "0";
                        txt_TienThue.Text = "0";
                        //Xoa het thong tin cua Phieu Dat tren nếu click phieu In sau khi luu
                    }
                }
            }
        }

        private string Lay_MaMoiNhat()
        {
            DataSet ds_tam = new DataSet();
            string mamoi;
            string maTam = "THNCC" + DateTime.Today.Year.ToString("0000") + DateTime.Today.Month.ToString("00");
            ds_tam.ReadXml(new StringReader(xuli.selectqueryByText("select top 1 MaTHNCC from PhieuTraHangNCC where MaTHNCC like '%" + maTam + "%'order by MaTHNCC desc")));
            if (ds_tam.Tables.Count == 0)
                mamoi = maTam + "0001";
            else
            {
                string matam = ds_tam.Tables[0].Rows[0][0].ToString();
                string kituso = matam.Substring(11, 4).ToString();
                int somoi = int.Parse(kituso) + 1;
                mamoi = maTam + somoi.ToString("0000");
            }
            return mamoi;
        }

        private void gv_ThongTinMatHangTra_CellEndEdit(object sender, GridViewCellEventArgs e)
        {
            
            try
            {
                double tongtien_sausua = 0;
                double dongia = double.Parse(gv_ThongTinMatHangTra.CurrentRow.Cells["DonGia"].Value.ToString());
                int soluong = int.Parse(gv_ThongTinMatHangTra.CurrentRow.Cells["SoluongTra"].Value.ToString().Trim());
                float khuyenmai = float.Parse(gv_ThongTinMatHangTra.CurrentRow.Cells["KhuyenMai"].Value.ToString());
                double thanhtien = (soluong * dongia) - ((soluong * dongia) * khuyenmai) / 100;
                gv_ThongTinMatHangTra.CurrentRow.Cells["ThanhTien"].Value = thanhtien.ToString("#,##0");

                for (int i = 0; i < gv_ThongTinMatHangTra.Rows.Count; i++)
                {
                    gv_ThongTinMatHangTra.Rows[i].Cells["SoluongTra"].Value = double.Parse(gv_ThongTinMatHangTra.Rows[i].Cells["SoluongTra"].Value.ToString()).ToString("#,##0");
                    gv_ThongTinMatHangTra.Rows[i].Cells["DonGia"].Value = double.Parse(gv_ThongTinMatHangTra.Rows[i].Cells["DonGia"].Value.ToString()).ToString("#,##0");
                    tongtien_sausua += double.Parse(gv_ThongTinMatHangTra.Rows[i].Cells["ThanhTien"].Value.ToString());
                }
                txt_TongTienHang.Text = tongtien_sausua.ToString("#,##0");
                if (txt_MucThue.Text.Length != 0)
                {
                    txt_TienThue.Text = (double.Parse(txt_MucThue.Text) * double.Parse(txt_TongTienHang.Text) / 100).ToString("#,##0");
                    txt_TongTienCoTinhThue.Text = (double.Parse(txt_TienThue.Text) + double.Parse(txt_TongTienHang.Text)).ToString("#,##0");


                }
                else
                {
                    txt_MucThue.Text = "0";
                    txt_TienThue.Text = (double.Parse(txt_MucThue.Text) * double.Parse(txt_TongTienHang.Text) / 100).ToString("#,##0");
                    txt_TongTienCoTinhThue.Text = double.Parse(txt_TongTienHang.Text).ToString("#,##0");
                }
                txt_TienBangChu.Text = So_chu(double.Parse(txt_TongTienCoTinhThue.Text));
            }
            catch
            {
            }
        }
        private void TextBoxKeyPress(object sender, KeyPressEventArgs e)
        {
            if (!Char.IsDigit(e.KeyChar) && !Char.IsControl(e.KeyChar))
            {
                e.Handled = true;
            }
        }
        private void gv_ThongTinMatHangTra_CellValueChanged(object sender, GridViewCellEventArgs e)
        {
            errorProvider1.Clear();
            try
            {
                for (int i = 0; i < ds_ton.Tables[0].Rows.Count; i++)
                {
                    if (ds_ton.Tables[0].Rows[i]["MaMH"].ToString().Trim() == gv_ThongTinMatHangTra.CurrentRow.Cells["MaMH"].Value.ToString().Trim())
                    {
                        if (int.Parse(gv_ThongTinMatHangTra.CurrentRow.Cells["SoLuongTra"].Value.ToString().Trim()) > int.Parse(ds_ton.Tables[0].Rows[i]["TongSLTon"].ToString().Trim()))
                        {
                            lbl_ThongBao.Text = "Số lượng nhập vào lớn hơn số lượng tồn. Vui lòng nhập lại";
                            errorProvider1.RightToLeft = false;
                            errorProvider1.SetError(lbl_ThongBao, "Xem lại thông tin trên lưới.");
                            return;
                        }
                    }                  
                }
                if (int.Parse(gv_ThongTinMatHangTra.CurrentRow.Cells["SoLuongTra"].Value.ToString().Trim())>kt_soluong)
                {
                    lbl_ThongBao.Text = "Số lượng nhập vào lớn hơn số lượng tồn. Vui lòng nhập lại";
                    errorProvider1.RightToLeft = false;
                    errorProvider1.SetError(lbl_ThongBao, "Xem lại thông tin trên lưới.");
                    return;
                }
                if (Regex.IsMatch(gv_ThongTinMatHangTra.CurrentRow.Cells["SoLuongTra"].Value.ToString().Trim(), @"^[0-9,',']{0,5}$") == false || int.Parse(gv_ThongTinMatHangTra.CurrentRow.Cells["SoLuongTra"].Value.ToString()) < 0)
                {
                    lbl_ThongBao.Text = "Số lượng nhập vào phải lớn hơn không (số lượng > 0) và là con số nguyên. Vui lòng nhập lại";
                    errorProvider1.RightToLeft = false;
                    errorProvider1.SetError(lbl_ThongBao, "Xem lại thông tin trên lưới.");
                    return;
                }
                if (Regex.IsMatch(gv_ThongTinMatHangTra.CurrentRow.Cells["DonGia"].Value.ToString(), @"^[0-9,',']{0,9}$") == false)
                {
                    lbl_ThongBao.Text = "Đơn giá nhập vào là số nguyên không âm. Vui lòng nhập lại";
                    errorProvider1.RightToLeft = false;
                    errorProvider1.SetError(lbl_ThongBao, "Xem lại thông tin trên lưới.");
                    return;
                }
                lbl_ThongBao.Text = "Thông báo!";
                errorProvider1.RightToLeft = true;
            }
            catch (Exception ex)
            {
                logger.Error("Error: " + ex.Message);
            }
        }

        private void gv_ThongTinMatHangTra_CommandCellClick(object sender, EventArgs e)
        {
            double tongtien_sauxoa = 0;
            try
            {
                if (MessageBox.Show("Bạn muốn xóa chi tiết này?", "Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    if (gv_ThongTinMatHangTra.Rows.Count == 1)
                    {
                        gv_ThongTinMatHangTra.Rows.Clear();
                    }
                    else
                    {
                        gv_ThongTinMatHangTra.Rows.RemoveAt(gv_ThongTinMatHangTra.CurrentRow.Index);
                        for (int i = 0; i < gv_ThongTinMatHangTra.Rows.Count; i++)
                        {
                            gv_ThongTinMatHangTra.Rows[i].Cells["STT"].Value = i + 1;
                        }
                    }
                    for (int j = 0; j < gv_ThongTinMatHangTra.Rows.Count; j++)
                    {
                        tongtien_sauxoa += double.Parse(gv_ThongTinMatHangTra.Rows[j].Cells["ThanhTien"].Value.ToString());
                    }
                    txt_TongTienHang.Text = tongtien_sauxoa.ToString("#,##0");

                }
            }
            catch (Exception ex)
            {
                logger.Error("Error: " + ex.Message);
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            mccb_NhaCungCap.Enabled = true;
            gv_ThongTinMatHangTra.Rows.Clear();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            mcbb_KhoHang.Enabled = true;
            gv_ThongTinMatHangTra.Rows.Clear();
        }

        private void txt_MucThue_TextChanged(object sender, EventArgs e)
        {
            if (txt_MucThue.Text.Length != 0)
            {
                txt_TienThue.Text = (double.Parse(txt_MucThue.Text) * double.Parse(txt_TongTienHang.Text) / 100).ToString("#,##0");
                txt_TongTienCoTinhThue.Text = (double.Parse(txt_TienThue.Text) + double.Parse(txt_TongTienHang.Text)).ToString("#,##0");


            }
            else
            {
                txt_MucThue.Text = "0";
                txt_TienThue.Text = (double.Parse(txt_MucThue.Text) * double.Parse(txt_TongTienHang.Text) / 100).ToString("#,##0");
                txt_TongTienCoTinhThue.Text = double.Parse(txt_TongTienHang.Text).ToString("#,##0");
            }
            txt_TienBangChu.Text = So_chu(double.Parse(txt_TongTienCoTinhThue.Text)); ;
        }

        private void txt_TongTienHang_TextChanged(object sender, EventArgs e)
        {
            if (txt_MucThue.Text.Length != 0)
            {
                txt_TienThue.Text = (double.Parse(txt_MucThue.Text) * double.Parse(txt_TongTienHang.Text) / 100).ToString("#,##0");
                txt_TongTienCoTinhThue.Text = (double.Parse(txt_TienThue.Text) + double.Parse(txt_TongTienHang.Text)).ToString("#,##0");


            }
            else
            {
                txt_MucThue.Text = "0";
                txt_TienThue.Text = (double.Parse(txt_MucThue.Text) * double.Parse(txt_TongTienHang.Text) / 100).ToString("#,##0");
                txt_TongTienCoTinhThue.Text = double.Parse(txt_TongTienHang.Text).ToString("#,##0");
            }
            txt_TienBangChu.Text = So_chu(double.Parse(txt_TongTienCoTinhThue.Text));
        }

        private void txt_tamung_TextChanged(object sender, EventArgs e)
        {
            if (txt_MucThue.Text.Length != 0)
            {
                txt_TienThue.Text = (double.Parse(txt_MucThue.Text) * double.Parse(txt_TongTienHang.Text) / 100).ToString("#,##0");
                txt_TongTienCoTinhThue.Text = (double.Parse(txt_TienThue.Text) + double.Parse(txt_TongTienHang.Text)).ToString("#,##0");


            }
            else
            {
                txt_MucThue.Text = "0";
                txt_TienThue.Text = (double.Parse(txt_MucThue.Text) * double.Parse(txt_TongTienHang.Text) / 100).ToString("#,##0");
                txt_TongTienCoTinhThue.Text = double.Parse(txt_TongTienHang.Text).ToString("#,##0");
            }
            txt_TienBangChu.Text = So_chu(double.Parse(txt_TongTienCoTinhThue.Text));
        }
        private void txt_DonGia_TextChanged(object sender, EventArgs e)
        {
            if (txt_SoLuongTra.Text.Length != 0)
            {
                if (txt_DonGia.Text.Length != 0)
                {
                    double thanhtien = double.Parse(txt_SoLuongTra.Text) * double.Parse(txt_DonGia.Text);
                    txt_ThanhTien.Text = thanhtien.ToString("#,##0");
                }
            }
        }

        private void btn_TimKiem_Click(object sender, EventArgs e)
        {
            try
            {
                frmBC_TraHangNCC trahangncc = new frmBC_TraHangNCC();
                trahangncc.Show();
            }
            catch (Exception ex)
            {

            }
        }

        private void btn_TaoMoi_Click(object sender, EventArgs e)
        {
            Load_Kho();
            Load_NCC();

            txt_SoChungTu.Text = "";
            dtp_NgayTra.Text = DateTime.Now.ToString();
            txt_DiaChiNhaCC.Text = "";
            txt_NguoiNhanTra.Text = "";
            txt_MaSoThue.Text = "";
            txt_Ghichu.Text = "";

            mccb_NhaCungCap.Enabled = true;
            mcbb_KhoHang.Enabled = true;
            mcbb_KhoHang.SelectedIndex = -1;
            mccb_NhaCungCap.SelectedIndex = -1;
            mccb_TenMatHang.SelectedIndex = -1;
            txt_MaMatHang.Text = "";
            txt_DonGia.Text = "0";
            txt_SoLuongTra.Text = "1";
            ddl_DVT.Text = "";
            txt_KhuyenMai.Text = "0";
            txt_ThanhTien.Text = "0";
            gv_ThongTinMatHangTra.Rows.Clear();

            txt_TienBangChu.Text = "Không chẵn";
            txt_TongTienHang.Text = "0";
            txt_MucThue.Text = "0";
            txt_TienThue.Text = "0";
            txt_TongTienCoTinhThue.Text = "0";
        }

        private void btn_XemIn_Click(object sender, EventArgs e)
        {
            try
            {
                DataSet ds = new DataSet();
                string mathncc = "";
                ds.ReadXml(new StringReader(xuli.selectqueryByText("select top 1 MaTHNCC from PhieuTraHangNCC order by MaTHNCC desc")));
                if (ds.Tables.Count > 0)
                {
                    mathncc = ds.Tables[0].Rows[0][0].ToString();
                    Report.frm_In_TraHangNCC trahangncc = new Report.frm_In_TraHangNCC();
                    trahangncc.MaTHNCC = mathncc;
                    trahangncc.ShowDialog();
                }
            }
            catch (Exception ex)
            {

            }
        }

        private void btn_DongForm_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btn_TimKiemDanhMucMH_Click(object sender, EventArgs e)
        {
            FormPhu_MatHang phuMH = new FormPhu_MatHang();
            phuMH.ShowDialog();
            if (phuMH.ShowDialog() == System.Windows.Forms.DialogResult.Cancel)
            {
                if (mccb_NhaCungCap.SelectedIndex != -1)
                {
                    if (mcbb_KhoHang.SelectedIndex != -1)
                    {
                        txt_DiaChiNhaCC.Text = mccb_NhaCungCap.EditorControl.Rows[mccb_NhaCungCap.SelectedIndex].Cells["diachincc"].Value.ToString();
                        DataSet ds = new DataSet();
                        ds.ReadXml(new StringReader(xuli.selectqueryByText("select MaMH,TenMH,DonGiaNhap from MatHang where MaMH in(select distinct MaMH from HoaDonNhapHang nh,CTNhapHang ct,NhaCungCap ncc where ct.MaHDNH=nh.MaHDNH and nh.MaNCC=ncc.MaNCC and ncc.MaNCC like '" + mccb_NhaCungCap.SelectedValue.ToString().Trim() + "%')")));
                        if (ds.Tables.Count > 0)
                        {
                            mccb_TenMatHang.DataSource = ds.Tables[0];
                            mccb_TenMatHang.DisplayMember = "TenMH";
                            mccb_TenMatHang.ValueMember = "MaMH";
                        }
                        DataSet ds1 = new DataSet();

                        ds1.ReadXml(new StringReader(xuli.BaoCaoXuatNhapTon(DateTime.Now, DateTime.Now, mcbb_KhoHang.SelectedValue.ToString().Trim(), mccb_TenMatHang.SelectedValue.ToString().Trim())));
                        if (ds1.Tables.Count > 0)
                        {
                            txt_SoLuongTra.Text = ds1.Tables[0].Rows[0]["TongSLTon"].ToString();
                        }
                        ds_ton = new DataSet();
                        ds_ton.ReadXml(new StringReader(xuli.BaoCaoXuatNhapTon(DateTime.Now, DateTime.Now, mcbb_KhoHang.SelectedValue.ToString().Trim(), "")));
                    }
                }
            }
        }
    }
}
